

import 'dart:io';

import 'package:fijkplayer/fijkplayer.dart';
import 'package:fimber/fimber.dart';
import 'package:video_player/video_player.dart';
import 'package:xim/common/get_style_view.dart';
import 'package:xim/common/util/security.dart';
import 'package:xim/http/apis/gfs/gfs_api.dart';

class VideoViewController extends GetxStateMixinController<dynamic>{

  /// 原始文件
  late File originalFile;

  /// 用于解密的密钥
  late String decodeKey;

  /// 视频Code
  final String videoCode;

  /// m3u8视频
  bool get isM3u8Format => videoCode.endsWith("m3u8");

  final FijkPlayer player = FijkPlayer();

  late VideoPlayerController videoPlayerController;

  VideoViewController(this.videoCode, this.decodeKey);

  /// aes 解密
  String decodeText(String cipherText, String aesKey) {
    return SecurityUtility.aes.decryptAes(encryptedBase64Text: cipherText, aseKey: aesKey);
  }

  @override
  Future<dynamic> dataInit() async {
    var downloadPath = GfsApi.getGfsFileDownloadPath(videoCode);
    originalFile = await GfsApi.downloadGfsFile(videoCode, usingCache: false);
    originalFile = await decodeM3u8Key(originalFile, (e)=>decodeText(e, decodeKey));
    videoPlayerController = VideoPlayerController.file(originalFile);
    videoPlayerController.initialize().then((value) {
      videoPlayerController.play();
    });
    player.setDataSource(downloadPath, autoPlay: true);
    return Future(() => null);
  }

  @override
  void dispose() {
    super.dispose();
    player.dispose();
    videoPlayerController.dispose();
  }

  Future<File> decodeM3u8Key(File m3u8File, String Function(String data) decode) async {
    List<String> lines = [];
    for(var line in m3u8File.readAsLinesSync()){
      if(line.startsWith("#EXT-X-KEY")){
        var spans = line.split(",");
        var span = spans[1];
        var keyFileName = span.substring(5, span.lastIndexOf("\""));
        var keyFile = await GfsApi.downloadGfsFile(keyFileName, usingCache: false);
        var key = keyFile.readAsStringSync().trim();
        var decodeKey = decode(key);
        await keyFile.writeAsString(decodeKey, mode: FileMode.writeOnly);
        spans[1] = "URI=\"${keyFile.path}\"";
        line = spans.join(",");
      }
      lines.add(line);
    }
    await m3u8File.writeAsString(lines.join("\n"));
    Fimber.i("m3u8 file content ${m3u8File.readAsStringSync()}");
    return m3u8File;
  }

}